﻿
#include <cdlog.h>
#include <cdroid.h>

#include <sys/syscall.h> // for SYS_xxx definitions
#include <unistd.h>      // for syscall()
#include <string.h>
#include <sys/prctl.h>

#include <project.h>
#include <conf_mgr.h>
#include <conn_mgr.h>
#include <curl_manager.h>
#include <wind_mgr.h>

#include "version.h"

///////////////////////////////////////////////////////////////////////////
class CTickHanlder : public EventHandler, public CURLCallback {
public:
    CTickHanlder() {
        mLastGetTimeClock = 0;
    }

    virtual int checkEvents() {
        static int64_t s_last_tick = SystemClock::uptimeMillis();
        int64_t now_tick = SystemClock::uptimeMillis();

        if (now_tick - s_last_tick >= 1000) {
            s_last_tick = now_tick;
            return 1;
        }

        return 0;
    }

    virtual int handleEvents() {
        int64_t now_tick = SystemClock::uptimeMillis();

        CConfMgr::ins()->update();
        WindowTime::ins()->updTime();
        checkWindow();

        if (now_tick - mLastGetTimeClock >= 30000) { getUTCTime(); }

        return 0;
    }

    virtual void onHttpResponse(int result, const std::string &body, void *data) {
        if (result) {
            // 网络异常
            g_appData.netOk = false;
            return;
        }

        // 网络连接成功
        // UTC时间 {"api":"mtop.common.getTimestamp","v":"*","ret":["SUCCESS::接口调用成功"],"data":{"t":"1687251120711"}}
        const char *pbody   = body.c_str();
        const char *begTime = strstr(pbody, "\"t\":\"");
        if (begTime) {
            int64_t timeMs = strtoll(begTime + sizeof("\"t\":\"") - 1, 0, 10);
            timeSet(timeMs / 1000 + 8 * HOUR_SECONDS); // 东八区
        }

        g_appData.netOk = true;
    }

    // 获取UTC时间
    void getUTCTime() {
        mLastGetTimeClock = SystemClock::uptimeMillis();
        g_objCURL->get("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp", this, 0);
    }

private:
    int64_t mLastGetTimeClock;
};

int main(int argc, const char **argv) {
    // 版本信息输出
    if (argc > 1 && strstr(argv[1], "version")) {
        printf("app_ver: %s app_key: %s\n", APP_VER_INFO, APP_KEY);
        return 0;
    }

    prctl(PR_SET_NAME, "main_thread");

    App app(argc, argv, g_stCustomCLA);

    LOG(ERROR) << "###程序模板(HW:xxxxxx)-APP:" << app.getName();

    // 配置
    CConfMgr::ins()->init();
    // http
    g_objCURL->init();
    // 平台通信
    g_objConnMgr->init();
    // 窗口
    g_objWindMgr->showMain();
    // 1s定时器
    CTickHanlder th;
    app.addEventHandler(&th);

    return app.exec();
}
